package xs.com.mylibrary.allinone.util;

import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;

public class WidgetUtil {
    /**
     * 动态设置ListView的高度 Item 必须是LinearLayout
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null)
            return;

        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public static void coverView(View child, View cover) {
        ViewParent parent = child.getParent();
        if (cover.getParent() != null)
            if (cover.getParent() instanceof LinearLayout) {
                LinearLayout cP = (LinearLayout) cover.getParent();
                cP.removeView(cover);
            } else if (cover.getParent() instanceof RelativeLayout) {
                RelativeLayout cP = (RelativeLayout) cover.getParent();
                cP.removeView(cover);
            } else if (cover.getParent() instanceof FrameLayout) {
                FrameLayout cP = (FrameLayout) cover.getParent();
                cP.removeView(cover);
            }

        if (parent instanceof LinearLayout) {
            LinearLayout p = (LinearLayout) parent;
            p.addView(cover, new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.FILL_PARENT));
        } else if (parent instanceof RelativeLayout) {
            RelativeLayout p = (RelativeLayout) parent;
            p.addView(cover, new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.FILL_PARENT,
                    RelativeLayout.LayoutParams.FILL_PARENT));
        } else if (parent instanceof FrameLayout) {
            FrameLayout p = (FrameLayout) parent;
            p.addView(cover, new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.FILL_PARENT,
                    FrameLayout.LayoutParams.FILL_PARENT));
        }
        child.setVisibility(View.GONE);
    }

}
